//
//  JinnengExamViewController.m
//  jinnengExam
//
//  Created by mac on 2020/8/12.
//  Copyright © 2020 jznrj. All rights reserved.
//

#import "JinnengExamViewController.h"
#import "ExamBottomView.h"
#import "ExamResultViewController.h"
@interface JinnengExamViewController ()<OperateBarDelegate,UINavigationControllerDelegate>
@property(nonatomic,strong) ExamBottomView *bottomView;

@property (nonatomic, strong) UIButton *  navrightBtn;
@property (nonatomic, strong) dispatch_source_t timer;
@property(nonatomic) BOOL canSubmit;

@end

@implementation JinnengExamViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    if (self.type == 1) {
        self.title = @"每日一练";
    }
    if (self.type == 2) {
        self.title = @"每周答题";
    }
    if (self.type == 3) {
        self.title = @"每月测试";
    }
    self.canSubmit = YES;
    [self initView];
    [self.navigationItem setLeftBarButtonItem:nil];
    [self.navigationItem setHidesBackButton:TRUE animated:NO];
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
    [self registerJSFunction];
    
}

-(void) viewWillAppear:(BOOL)animated{
    self.navigationController.navigationBar.hidden = NO;
    self.tabBarController.tabBar.frame = CGRectMake(0, 0, 0, 0);
    self.tabBarController.tabBar.hidden = YES;
}

-(void)viewDidDisappear:(BOOL)animated{
    dispatch_source_cancel(self.timer);
    self.timer = nil;
}

-(void) initView{
    [self.view addSubview:self.jznWebView];
    self.jznWebView.scrollView.bounces = NO;
    [self.jznWebView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.view);
        make.bottom.equalTo(self.view).offset(-52);
    }];

    
    self.bottomView = [[ExamBottomView alloc]init];
    self.bottomView.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin;
    self.bottomView.delegate = self;
    [self.view addSubview:self.bottomView];
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        if (@available(iOS 11.0, *)) {
            make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom);
        } else {
            make.bottom.equalTo(self.view);
        }
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(52);
    }];
    [self.bottomView setUpView];
  
    [self.view addSubview:self.loadingProgressView];
    [self.loadingProgressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.view);
    }];
    
    self.view.backgroundColor = [UIColor whiteColor];
    [self.jznWebView loadLocalFile:@"/ios_jinneng/jinnengAnswer" type:@"html"];
    
    self.navrightBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 80, 30)];
    [self.navrightBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 20, 0, -10)];
    self.navrightBtn.titleLabel.textAlignment=NSTextAlignmentRight;
    [self.navrightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.navrightBtn.titleLabel.font=[UIFont systemFontOfSize:14];
    [self.navrightBtn setTitle:@"" forState:UIControlStateNormal];
    UIBarButtonItem *naviItem = [[UIBarButtonItem alloc] initWithCustomView:self.navrightBtn];
    self.navigationItem.rightBarButtonItem=naviItem;
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
             _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
             dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
             dispatch_source_set_event_handler(_timer, ^{
                 if(self.time ==0) {
                     NSString *showAnswer = @"submitTest()";
                     [self.jznWebView evaluateJavaScript:showAnswer completionHandler:nil];
                     return;
                 }
                 int second = self.time%60;
                 int min = self.time/60;
                 NSString *strTime;
                 
                 if (min < 10 && second <10){
                     strTime = [NSString stringWithFormat:@"0%d: 0%d",min,second];
                 }else if (second <10) {
                     strTime = [NSString stringWithFormat:@"%d: 0%d",min,second];
                 }else if (min < 10){
                     strTime = [NSString stringWithFormat:@"0%d: %d",min,second];
                 }else{
                     strTime = [NSString stringWithFormat:@"%d: %d",min,second];
                     
                 }
                 
                 dispatch_async(dispatch_get_main_queue(), ^{
                     //设置界面的按钮显示 根据自己需求设置
                     
                     [self.navrightBtn setTitle:strTime forState:UIControlStateNormal];
                     
                 });
                 self.time--;
                 
             });
             dispatch_resume(_timer);
    
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation{
    NSString *js = [NSString stringWithFormat:@"loadPaper(%@)",self.paper];
    [self.jznWebView evaluateJavaScript:js completionHandler:nil];
}

-(void) registerJSFunction{
    [self.webViewBridge registerHandler:@"indexError" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSString *error = data[@"errorMessage"];
        dispatch_async(dispatch_get_main_queue(), ^(){
            [[UIApplication sharedApplication].delegate.window makeToast:error];
        });
    }];
    
    [self.webViewBridge registerHandler:@"submitResult" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSMutableDictionary *paper = [data[@"result"] mutableCopy];
        
        int correct = 0;
        int uncorrect = 0;
        int unanswer = 0;
        NSMutableArray *examQuetionRedisDtoList = [paper[@"questionList"] mutableCopy];
        for(int i = 0;i<[examQuetionRedisDtoList count];i++){
            NSMutableDictionary *question = [[examQuetionRedisDtoList objectAtIndex:i] mutableCopy];
            NSArray *answerList = question[@"answerList"];
            NSString *selected = @"";
            for(NSDictionary *answer in answerList){
                if([answer[@"selected"] boolValue] ){
                    selected = [NSString stringWithFormat:@"%@%@",selected,answer[@"optionName"]];
                }
            }
            //[question removeObjectForKey:@"userAnswer"];
            [question setObject:selected forKey:@"userAnswer"];
            if ([selected isEqualToString:@""]) {
                unanswer++;
            } else if ([selected isEqualToString:question[@"solution"]]) {
                correct++;
            }else {
                uncorrect++;
            }
            examQuetionRedisDtoList[i] = question;
        }
        [paper setObject:examQuetionRedisDtoList forKey:@"questionList"];
        [paper setObject:[NSString stringWithFormat:@"%d",[examQuetionRedisDtoList count]] forKey:@"total"];
        [paper setObject:[NSString stringWithFormat:@"%d",correct] forKey:@"correct"];
        [paper setObject:[NSString stringWithFormat:@"%d",uncorrect] forKey:@"uncorrect"];
        [paper setObject:[NSString stringWithFormat:@"%d",unanswer] forKey:@"unanswer"];
        [paper setObject:[NSString stringWithFormat:@"%d",self.tradeId] forKey:@"tradeId"];
        [self submitResult:paper];
    }];

}

-(void) submitResult:(NSDictionary*) result{
    NSString *url = [NSString stringWithFormat:@"%@/studentExam/submitUserPaper",[URLUtil hostName]];
    NSDictionary *params = @{@"examPaperRedisDto":result,
                             @"examType":[NSString stringWithFormat:@"%d",self.type],
                             @"userId":[NSString stringWithFormat:@"%d",self.loginDto.userId]};
    [self.loadingProgressView startAnimating];
    [JZNRequestUtil requestUrl:url requestParams:params success:^(DataResult *dataResult) {
        [self.loadingProgressView stopAnimating];
        if(dataResult.code == 0){
            dispatch_async(dispatch_get_main_queue(), ^(){
                ExamResultViewController *vc = [[ExamResultViewController alloc]init];
                vc.paper = [result mj_JSONString];
                [self.navigationController pushViewController:vc animated:YES];
            });
        }else {
        }
    } failure:^(NSError *error) {
        
    }];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
- (void)onButtonAction:(NSInteger)offset{
    if (offset == 0) {
        
        NSString *pre = @"pre()";
        [self.jznWebView evaluateJavaScript:pre completionHandler:nil];
    }else if(offset == 1){
        
        NSString *next = @"next()";
        [self.jznWebView evaluateJavaScript:next completionHandler:nil];
        
    } else if(offset == 2) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"确定提交成绩吗?" preferredStyle:  UIAlertControllerStyleAlert];
        
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSString *showAnswer = @"submitTest()";
            [self.jznWebView evaluateJavaScript:showAnswer completionHandler:nil];
        }]];
        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        }]];
        
        [self presentViewController:alert animated:true completion:nil];
    
    }
}
@end
